<template>
  <jke-modal
      :visible.sync="jkeForm.visible"
      :width="1200"
      :title="jkeForm.title"
      :fullscreen.sync="jkeForm.fullscreen"
      :switchFullscreen="jkeForm.switchFullscreen"
    >
    <!--  -->
    <crumbs
      @goBack="goBack"
      :superiorMenu="['设备管理', '设备点巡检', '检查']"
      marginBottom="10px"
      currentMenu="新建检查"
    ></crumbs>
    <div class="form-body">
      <a-card title="基本信息" :bordered="false">
        <a-form :form="form" @submit="handleSubmit" layout="vertical">
          <a-form-item label="点巡检设备">
            <a-input
              @click="openIt"
              v-decorator="['deviceCodeName', { rules: [{ required: true, message: '请选择' }] }]"
              placeholder="请选择"
              :read-only="true"
              :class="goodsTextEQ ? 'has-value' : ''"
            >
              <a-icon slot="suffix" type="down" style="color: #cdcdcd; font-size: 12px" class="down-icon" />
              <a-icon
                slot="suffix"
                type="close-circle"
                theme="filled"
                class="close-icon"
                @click="getSelectValueEQ(false, '', [])"
              />
            </a-input>
          </a-form-item>
          <a-form-item label="设备类别" prop="deviceCategoryText">
            <a-input :disabled="true" v-decorator="['deviceCategoryText']" placeholder="请选择点巡检设备" />
          </a-form-item>
          <a-form-item label=""> </a-form-item>
        </a-form>
      </a-card>
      <a-card title="点巡检项目" :bordered="false" style="margin-top: 12px">
        <j-editable-table
          ref="goodsTable"
          :loading="goodsTable.loading"
          :columns="goodsTable.columns"
          :dataSource="goodsTable.dataSource"
          :maxHeight="300"
          :rowNumber="true"
          :actionButton="true"
          @valueChange="valueChange"
        >
          <template v-slot:action="props">
            <a-popconfirm title="是否删除?" ok-text="是" cancel-text="否" @confirm="handleDeleteGood(props)">
              <span class="del-text">删除</span>
            </a-popconfirm>
          </template>

          <template v-slot:projectCode="props">
            <a-input
              placeholder="请选择"
              :read-only="true"
              @click="showSelect(props)"
              :value="projectNameText(props)"
              :class="projectNameText(props) ? 'has-value' : ''"
            >
              <a-icon slot="suffix" type="down" style="color: #cdcdcd; font-size: 12px" class="down-icon" />
              <a-icon
                slot="suffix"
                type="close-circle"
                theme="filled"
                class="close-icon"
                @click="getSelectValue(false, '', [], props.rowId)"
              />
            </a-input>
            <tableSelect
              ref="tableSelect"
              @getSelectValue="(id, text, item) => getSelectValue(id, text, item, props.rowId)"
              :key="selectIndex"
            >
              <!-- <div slot="head">我是插槽，写入搜索重置等功能</div> -->
              <div slot="head">
                <div class="uni-card" style="background: #fff">
                  <a-form-model ref="ruleForm" layout="inline" :model="filterForm">
                    <a-form-model-item label="项目编号">
                      <a-input v-model="filterForm.projectCode" placeholder="请输入" />
                    </a-form-model-item>
                    <a-form-model-item label="项目名称">
                      <a-input v-model="filterForm.projectName" placeholder="请输入" />
                    </a-form-model-item>
                    <a-form-model-item>
                      <a-button @click="searchGoods()" type="primary"> 搜索 </a-button>
                      <a-button style="margin-left: 10px" @click="searchResetGoods">重置</a-button>
                    </a-form-model-item>
                  </a-form-model>
                </div>
              </div>
            </tableSelect>
          </template>
        </j-editable-table>
      </a-card>
      <a-card title="其他信息" :bordered="false" style="margin-top: 12px">
        <a-form :form="form" @submit="handleSubmit" layout="vertical">
          <a-form-item label="备注" style="flex: 1">
            <a-textarea placeholder="请输入" :maxLength="500" auto-size v-decorator="['remark']" />
          </a-form-item>
        </a-form>
        <a-form layout="vertical">
          <a-form-item label="附件" style="flex: 1">
            <file-upload :ids="attachment" @getFileList="getFileList"></file-upload>
            <p style="line-height: 30px;color:#8d8d8d;">最多上传5个文件，大小不可超过20M</p>
          </a-form-item>
        </a-form>
      </a-card>
    </div>
    <div class="footer-submit form-footer">
      <a-button type="primary" :loading="loadingSubmit" @click="handleSubmit()"> 提交 </a-button>
    </div>
    <tableSelect ref="tableSelectEQ" @getSelectValue="getSelectValueEQ" :key="indexEQ">
      <div slot="head">
        <div class="uni-card" style="background: #fff">
          <a-form-model ref="ruleForm" layout="inline" :model="filterFormEQ">
            <a-form-model-item label="设备编号">
              <a-input v-model="filterFormEQ.deviceCode" placeholder="请输入" />
            </a-form-model-item>
            <a-form-model-item label="设备名称">
              <a-input v-model="filterFormEQ.deviceName" placeholder="请输入" />
            </a-form-model-item>
            <a-form-model-item>
              <a-button @click="searchEquip()" type="primary"> 搜索 </a-button>
              <a-button style="margin-left: 10px" @click="searchResetEquip">重置</a-button>
            </a-form-model-item>
          </a-form-model>
        </div>
      </div>
    </tableSelect>
  </jke-modal>
</template>
<script>
import crumbs from '@/components/crumbs.vue'
import FileUpload from '@/components/fileActions/FileUpload.vue'
import { API } from '@/api/requestFzs'
import { APILX } from '@/api/requestLx'
import moment from 'dayjs'
import JEditableTable from '@/components/jeecg/JEditableTable.vue'
import { validateTables, FormTypes, VALIDATE_NO_PASSED } from '@/utils/JEditableTableUtil'
import { fourFloatNum, validateDuplicateValue, checkPrice } from '@/utils/util'
import tableSelect from '@/components/tableSelect'
export default {
  data() {
    return {
      jkeForm: {
        title: '新建检查',
        visible: false,
        fullscreen: true,
        switchFullscreen: true,
      },
      //下拉改弹窗
      indexEQ: 0,
      columnsEQ: [
        {
          title: '设备编号',
          // align: 'center',
          dataIndex: 'deviceCode',
        },
        {
          title: '设备名称',
          // align: 'center',
          dataIndex: 'deviceName',
        },
        {
          title: '规格',
          // align: 'center',
          dataIndex: 'spec',
        },
        {
          title: '购买日期',
          // align: 'center',
          dataIndex: 'purchaseDate',
        },
        {
          title: '保修期(月)',
          // align: 'center',
          dataIndex: 'warranty',
        },
      ],
      goodsValueEQ: '',
      goodsTextEQ: '',
      filterFormEQ: {
        deviceCode: '', //设备编号
        deviceName: '', //设备名称
      },
      //下拉改弹窗结束
      validateDuplicateValue,
      formLayout: 'horizontal',
      form: this.$form.createForm(this, { name: 'task' }),
      attachment: '',
      submitApi: APILX.messDeviceCheckTaskAdd,
      isEdit: false,
      loadingSubmit: false,
      customSelectList: [],
      goodsTable: {
        loading: false,
        dataSource: [{}],
        columns: [
          {
            title: '项目Id',
            key: 'itemId',
            type: FormTypes.hidden,
          },
          {
            title: '点巡检项',
            key: 'projectCode',
            type: FormTypes.slot,
            placeholder: '请选择',
            slotName: 'projectCode',
            options: [],
            isrequired: true,
            allowSearch: true,
            defaultValue: '',
            validateRules: [{ required: true, message: '${title}不能为空' }],
          },
          {
            title: '检查标准',
            key: 'checkStandard',
            type: FormTypes.input,
            disabled: true,
            placeholder: '请选择项目',
            slotName: 'checkStandard',
            defaultValue: '',
          },
          {
            title: '检查结果',
            key: 'checkResults',
            // width: '18%',
            isrequired: true,
            type: FormTypes.select,
            options: [
              // 下拉选项
              { title: '正常', value: '0' },
              { title: '异常', value: '1' },
            ],
            allowInput: true,
            defaultValue: '',
            placeholder: '请选择${title}',
            validateRules: [{ required: true, message: '请选择${title}' }],
          },
          {
            title: '操作',
            key: 'action',
            type: FormTypes.slot,
            placeholder: '选择${title}',
            slotName: 'action',
            defaultValue: '',
          },
        ],
      },
      queryId: '', // 校验编号唯一ID
      examineType: '0',
      allGoods: [],
      goodsProps: {},
      selectIndex: 0,
      selectColumns: [
        {
          title: '项目编号',
          // align: 'center',
          dataIndex: 'projectCode',
        },
        {
          title: '项目名称',
          // align: 'center',
          dataIndex: 'projectName',
        },
        {
          title: '检查标准',
          // align: 'center',
          dataIndex: 'checkStandard',
        },
        {
          title: '创建时间',
          // align: 'center',
          dataIndex: 'createTime',
        },
        // {
        //   title: '创建人',
        //   align: 'center',
        //   dataIndex: 'createByTxt',
        // },
      ],
      filterForm: {},
    }
  },
  components: {
    FileUpload,
    crumbs,
    JEditableTable,
    tableSelect,
  },
  methods: {
    // 点巡检设备下拉改弹窗
    searchResetEquip() {
      this.filterFormEQ.deviceCode = ''
      this.filterFormEQ.deviceName = ''
      this.$refs.tableSelectEQ.searchReset()
    },
    searchEquip() {
      this.$refs.tableSelectEQ.searchQuery(this.filterFormEQ)
    },
    openIt() {
      let par = {
        list: '/mess/device/list',
        visible: true, //弹窗开启
        title: '点巡检设备', //标题名称
        multi: false, //是否多选
        columns: this.columnsEQ, //表格配置
        value: this.goodsValueEQ, //需要回显的数据，如：id:'12323213,321312312,321312312'
        valueKey: 'id', //需要拿到数据的key，如：id，userId等
        text: this.goodsTextEQ, //回显的中文，如：'张三'
        textKey: 'deviceName', //回显的中文key
      }
      this.$refs.tableSelectEQ.getInit(par)
    },
    getSelectValueEQ(id, text, item) {
      if (!id) {
        this.form.setFieldsValue({
          deviceCodeName: '',
          deviceCategoryText: '',
        })
        this.goodsTextEQ = ''
        this.goodsValueEQ = ''
        return
      }
      this.indexEQ += 1 //重置组件去除表格默认勾选数据，让自己赋值的数据回显（重要！！！）
      this.goodsValueEQ = id
      this.goodsTextEQ = `${item[0].deviceCode}-${item[0].deviceName}`
      console.log(this.goodsTextEQ, 'this.goodsTextEQ')
      console.log(this.goodsValueEQ, 'this.goodsValueEQ')
      this.form.setFieldsValue({
        deviceCodeName: `${item[0].deviceCode}-${item[0].deviceName}`,
        deviceCategoryText: item[0].deviceCategoryText,
      })
      console.log(id, text, item, '列表选择的数据')
    },
    // 重置
    searchResetGoods() {
      this.filterForm = {}
      this.$refs.tableSelect.searchReset()
    },
    // 筛选
    searchGoods() {
      this.$refs.tableSelect.searchQuery(this.filterForm)
    },
    // 点击选择项目下拉框，弹出选择组件
    showSelect(p) {
      this.goodsProps = p
      var tableValue = this.$refs.goodsTable.getValuesSync({ validate: false, rowIds: [this.goodsProps.rowId] })
        .values[0]
      let par = {
        list: '/mess/messCheckItem/list',
        visible: true, //弹窗开启
        title: '点巡检项目', //标题名称
        multi: false, //是否多选
        columns: this.selectColumns, //表格配置
        value: tableValue.projectCode || '', //需要回显的数据，如：id:'12323213,321312312,321312312'
        valueKey: 'id', //需要拿到数据的key，如：id，userId等
        text: tableValue.projectName, //回显的中文，如：'张三'
        textKey: 'projectName', //回显的中文key
      }
      this.$refs.tableSelect.getInit(par)
    },
    // 选择项目回调
    getSelectValue(id, text, item, rowId) {
      this.selectIndex += 1 //重置组件去除表格默认勾选数据，让自己赋值的数据回显（重要！！！）
      if (!id) {
        this.$refs.goodsTable.setValues([
          {
            rowKey: rowId, // 行的id
            values: {
              // 在这里 values 中的 goodsId 是你 columns 中配置的 key
              itemId: '',
              projectCode: '',
              checkStandard: '',
            },
          },
        ])
        return
      }
      this.$refs.goodsTable.setValues([
        {
          rowKey: this.goodsProps.rowId, // 行的id
          values: {
            // 在这里 values 中的 goodsId 是你 columns 中配置的 key
            itemId: item[0].id,
            projectCode: `${item[0].projectCode}-${item[0].projectName}`,
            checkStandard: item[0].checkStandard,
          },
        },
      ])
      this.setGoodsInfo(id)
      console.log(id, text, item, this.goodsProps.rowId, '列表选择的数据')
    },
    // 根据选择的项目带出其他商品信息并填充
    setGoodsInfo(value) {
      var tableValue = this.$refs.goodsTable.getValuesSync({ validate: false }).values
      var newArr = []
      tableValue.forEach((v) => {
        newArr.push(v.itemId)
      })
      var newArrLen = [...new Set(newArr)].length
      var oldArrLen = tableValue.length
      if (newArrLen < oldArrLen) {
        this.$refs.goodsTable.removeRows(this.goodsProps.rowId)
        this.$antdMessage.warning('该项目已存在')
        return
      }
      this.$refs.goodsTable.getValuesSync({ validate: true })
    },
    // 项目选择框回显值
    projectNameText(p) {
      var item = this.$refs.goodsTable.getValuesSync({ validate: false, rowIds: [p.rowId] }).values[0]
      console.log('itemssssss:', p.rowId)
      return `${item.projectCode ? item.projectCode : ''}${item.projectName ? item.projectName : ''}`
    },
    // 下拉搜索
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    handleDeleteGood(p) {
      this.$refs.goodsTable.removeRows(p.rowId)
      this.selectIndex += 1 //重置组件去除表格默认勾选数据，让自己赋值的数据回显（重要！！！）
    },
    valueChange(type) {
      if (type.column.key == 'saleNum') {
        this.$refs.goodsTable.setValues([
          {
            rowKey: type.row.id, // 行的id
            values: {
              // 在这里 values 中的 specifications 是你 columns 中配置的 key
              saleNum: fourFloatNum(type.value),
            },
          },
        ])
      }
      return
      if (type.column.key == 'goodsId') {
        if (!type.value) {
          this.$refs.goodsTable.setValues([
            {
              rowKey: type.row.id, // 行的id
              values: {
                // 在这里 values 中的 specifications 是你 columns 中配置的 key
                basicUnit: '',
                unit: '',
                unitId: '',
              },
            },
          ])
          return
        }
        var goodSelectItem = this.goodsTable.columns[0].options.find((item) => item.value === type.value)
        var tableValue = this.$refs.goodsTable.getValuesSync({ validate: false }).values
        var newArr = []
        tableValue.forEach((v) => {
          newArr.push(v.goodsId)
        })
        var newArrLen = [...new Set(newArr)].length
        var oldArrLen = tableValue.length
        if (newArrLen < oldArrLen) {
          this.$refs.goodsTable.removeRows(type.row.id)
          this.$antdMessage.warning('该商品已存在，请直接修改数据')
          return
        }
        var hasGood = false
        API.findUnitListByGoodsId({ goodsId: type.value }).then((res) => {
          for (let i = 0; i < this.allGoods.length; i++) {
            const item = this.allGoods[i]
            if (item.goodsId == type.value) {
              hasGood = true
            }
          }
          if (!hasGood) {
            this.allGoods.push({
              goodsId: type.value,
              unitList: res.result,
            })
            var unitObj = res.result.find((u) => u.unitType == 'basic_unit')
            this.$refs.goodsTable.setValues([
              {
                rowKey: type.row.id, // 行的id
                values: {
                  // 在这里 values 中的 specifications 是你 columns 中配置的 key
                  basicUnit: 'basic_unit',
                  unit: unitObj.unit || '',
                  unitId: unitObj.id,
                },
              },
            ])
          }
        })
      }
    },
    /* 下拉数据 */
    getGoods() {
      /* 获取商品下拉数据 */
      API.getAllGoodsBaseInfo({ pageSize: 999, pageNo: 1 }).then((res) => {
        if (res.code == 200) {
          if (res.result.records) {
            this.goodsTable.columns[0].options = []
            res.result.records.forEach((item) => {
              // item.title = item.goodsName
              item.title = `${item.goodsCode ? item.goodsCode + ' | ' : ''}${
                item.goodsName ? item.goodsName + ' | ' : ''
              }${item.spec ? item.spec : ''}`
              item.text = `${item.goodsCode ? item.goodsCode + ' | ' : ''}${
                item.goodsName ? item.goodsName + ' | ' : ''
              }${item.spec ? item.spec : ''}`
              item.value = item.id
              this.goodsTable.columns[0].options.push(item)
            })
          }
          // this.goodsTable.columns[0].options = res.result.records || []
        } else {
          this.$antdMessage.error(res.message)
        }
      })
      /* 客户下拉 */
      API.erpCustomerList({ pageSize: 999, pageNo: 1, effectStatus: 'effective' }).then((res) => {
        if (res.code == 200) {
          this.customSelectList = res.result.records
        }
      })
    },
    /* 选择物料后查询带出物料信息 */
    selectChange(v) {
      if (!v) {
        this.form.setFieldsValue({
          spec: '-',
          basicUnitText: '-',
          typeText: '-',
          categoryText: '-',
          goodsId: '',
        })
        return
      }
    },
    selectCustom(v) {
      console.log(v)
    },
    /* 面包屑返回 */
    goBack() {
      this.jkeForm.visible = false
    },
    /* 获取编辑详情 */
    initForm(id) {
      this.jkeForm.visible = true
      this.getGoods()
      if (id) {
        this.queryId = id
        this.examineType = '1'
        this.jkeForm.title = '编辑检查'
        this.submitApi = API.erpSaleContractEdit
        this.isEdit = true
        API.erpSaleContractQueryById({ id: id }).then((res) => {
          if (res.code == 200) {
            let editForm = res.result
            editForm.signUserCode = editForm.signUserCode
            this.$nextTick(() => {
              this.form.setFieldsValue(editForm)
            })
            this.attachment = res.result.attachment
            let newGoodsList = res.result.erpSaleContractEditVoList
            for (let i = 0; i < newGoodsList.length; i++) {
              const good = newGoodsList[i]
              good.basicUnit = good.unitType
              good.unitList = JSON.stringify(good.unitList)
            }
            this.allGoods = newGoodsList
            this.goodsTable.dataSource = newGoodsList
            console.log(newGoodsList)
          }
        })
      } else {
        this.jkeForm.title = '新建检查'
        this.form.setFieldsValue({
          qualityTestProcess: '1',
        })
      }
    },
    /* 获取附件 */
    getFileList(v) {
      this.attachment = v
      console.log('上传的附件id：', v)
    },
    // 提交
    handleSubmit() {
      let errArr = []
      let parameters = {}
      let { error, values } = this.$refs.goodsTable.getValuesSync({ validate: true })
      if (error === 0) {
      } else {
        errArr.push(false)
      }
      this.form.validateFields((err, formValues) => {
        if (!err) {
          parameters = { ...formValues, attachment: this.attachment, deviceId: this.goodsValueEQ }
          if (this.isEdit) {
            parameters.id = this.queryId
          } else {
          }
          if (errArr.length == 0) {
            let messDeviceCheckTaskItemList = values.map((g, i) => {
              return {
                checkResults: g.checkResults,
                itemId: g.id,
                projectCode: g.projectCode,
                projectName: g.projectName,
                checkStandard: g.checkStandard,
              }
            })
            parameters.messDeviceCheckTaskItemList = messDeviceCheckTaskItemList
            console.log(parameters, 'param 0.0 .0.0.0.0')
            this.loadingSubmit = true
            this.submitApi(parameters).then((res) => {
              this.loadingSubmit = false
              if (res.code == 200) {
                let subMsg = this.isEdit ? '编辑成功！' : '新建成功！'
                this.$antdMessage.success(subMsg)
                this.$emit('refresh')
                this.goBack()
              } else {
                this.$antdMessage.error(res.message)
              }
            })
          }
        } else {
        }
      })
    },
  },
}
</script>
<style scoped lang="less">
@import '~@/assets/less/public.less';
/deep/.ant-form-vertical {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  .ant-form-item {
    width: 30%;
  }
}
.form-body {
  height: calc(100vh - 120px);
  overflow-y: scroll;
}
.code-btn {
  position: absolute;
  right: 0;
  top: -34.5px;
}
</style>
